import json
import random

import pymysql
from django.test import TestCase

# Create your tests here.


# -*- coding: utf-8 -*-
# @Author: fanmingxiang@touty.io
# @Date: 2023/3/14 10:55
import json
import os
import unittest
from datetime import datetime

from ddt import ddt, unpack, file_data, data
import requests
from parameterized import parameterized

from htmltestreport import HTMLTestReport

filepath = r"F:\Pycharm\workspace\ApiAutoTestPlatform\apitests\templates\json\case_data.json"


class ParameterTest(unittest.TestCase):
    # 重写init方法，补充额外参数
    # 接受参数定义为对象属性
    def __init__(self, method):
        # 复用父类 unittest.TestCase init方法
        super(ParameterTest, self).__init__(method)

    def get_sql(self):
        a = ("MAC", "2", "13661551222"), ("MAC", "2", "13662231222"), ("MAC", "2", "13631231222"), (
            "MAC", "2", "13631231222")

        return a


@ddt
class TestAutoCase(ParameterTest):
    @classmethod
    def setUpClass(cls) -> None:
        cls.session = requests.session()

    @classmethod
    def tearDownClass(cls) -> None:
        cls.session.close()

    @unpack
    @file_data(filepath)
    # @parameterized.expand(read_json("case_data.json"))
    def test_auto_case(self, method, url, headers, params, body_type, body, is_assert, assert_type, assert_body):
        print(id(filepath))
        if method == "GET":
            try:
                response = self.session.get(url, headers=headers, params=params)
                if is_assert == 1:
                    if assert_type == 0:
                        self.assertEqual(assert_body, response.text)
                    elif assert_type == 1:
                        self.assertIn(assert_body, response.text)
                    else:
                        self.assertEqual(int(assert_body), response.status_code)
            except AssertionError as e:
                raise e
        if method == "POST":
            try:
                if body_type == 2:
                    response = self.session.post(url, headers=headers, params=params, json=body)
                else:
                    response = self.session.post(url, headers=headers, params=params, data=body)
                if is_assert == 1:
                    if assert_type == 0:
                        self.assertEqual(assert_body, str(response.json()))
                    elif assert_type == 1:
                        self.assertIn(assert_body, str(response.json()))
                    else:
                        self.assertEqual(int(assert_body), response.status_code)
            except AssertionError as e:
                raise e


#
if __name__ == '__main__':
    conn = pymysql.connect(host='localhost', password='123456', port=3306, user='root', db="ApiAutoTestPlatform",
                           charset='utf8')
    cursor = conn.cursor()
    sql = "SELECT * from test_reports_testreports order by create_time desc limit 0,1;"
    cursor.execute(sql)
    data = cursor.fetchone()
    report_url = str(random.randint(1000000000, 9999999999)) + '.html'
    report_path = r'F:\Pycharm\workspace\ApiAutoTestPlatform\apitests\templates\report' + os.sep + report_url
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestAutoCase))
    html_report = HTMLTestReport(report_path, data[1])
    report = html_report.run(suite)
    print(report)
    sql1 = "update test_reports_testreports set test_all_count=%s, success_count=%s," \
           "failure_count=%s, error_count=%s, skip_count=%s, " \
           "startTime = '%s', stopTime='%s'," \
           "status=1, report_url='%s'" \
           " where id=%d;" % (report.testsRun, report.success_count, report.failure_count,
                              report.error_count, report.skip_count, html_report.startTime, html_report.stopTime,
                              report_url,
                              data[0])
    cursor.execute(sql1)
    for result in report.result:
        sq2 = "insert into test_reports_reportdescribe(name, error_msg, status,test_report_id,create_time) " \
              "values ('%s', '%s', '%s', %d, '%s') " % (
                  result[1], result[3], result[0], data[0], datetime.now())
        cursor.execute(sq2)
    conn.commit()
    cursor.close()
    conn.close()
